package com.dindang.propertyfee.mvp.presenter;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.alibaba.android.arouter.launcher.ARouter;
import com.dindang.propertyfee.R;
import com.dindang.propertyfee.app.AppConst;
import com.dindang.propertyfee.app.utils.print.AidlUtil;
import com.dindang.propertyfee.mvp.contract.ReceivableDetailContract;
import com.dindang.propertyfee.mvp.model.entity.BaseResponse;
import com.dindang.propertyfee.mvp.model.entity.ProperFeeEvent;
import com.dindang.propertyfee.mvp.model.entity.PropertyCharge;
import com.dindang.propertyfee.mvp.ui.adapter.custom.ReceivableDetailViewAdapter;
import com.dindang.propertyfee.mvp.ui.widget.PaymentSelectDialog;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.RxLifecycleUtils;
import com.longxi.gamer_base.BaseAppConst;
import com.longxi.gamer_base.MyApplication;
import com.longxi.gamer_base.dialog.WaitDialog;
import com.longxi.gamer_base.utils.DoubleUtil;

import org.greenrobot.eventbus.EventBus;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import me.jessyan.rxerrorhandler.handler.RetryWithDelay;


@ActivityScope
public class ReceivableDetailPresenter extends BasePresenter<ReceivableDetailContract.Model, ReceivableDetailContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    List<PropertyCharge.NodedataDetail.Bills> mCostItems = new ArrayList<>();
    List<PropertyCharge.NodedataDetail.Bills> mShoukuan = new ArrayList<>();//存储需要收款的数据
    ReceivableDetailViewAdapter mAdapter;
    private PropertyCharge.QueryByNodedataIdParam mParam = new PropertyCharge.QueryByNodedataIdParam();
    private PropertyCharge.PayCashPara mParamCash = new PropertyCharge.PayCashPara();
    double totalPrice = 0.00;
    boolean isSelectAll = false;
    private InputMethodManager mImm;
    private String mPhone;
    private List<PropertyCharge.RecordDetail> mRecordDetailList = new ArrayList<>();
    private StringBuffer content;
    private PropertyCharge.RecordDetail mRecordDetail;
    private String[] mCollectionType = {"", "现金", "POS", "微信", "支付宝", "银行转账"};
    private PropertyCharge.GetDetailPara mParamdetail = new PropertyCharge.GetDetailPara();
    PropertyCharge.NodedataDetail mData = new PropertyCharge.NodedataDetail();
    String payname;
    private WaitDialog mWaitDialog;
    private ProperFeeEvent properFeeEvent = new ProperFeeEvent();

    @Inject
    public ReceivableDetailPresenter(ReceivableDetailContract.Model model, ReceivableDetailContract.View rootView) {
        super(model, rootView);
    }

    public void init() {
        mWaitDialog = new WaitDialog(mRootView.getActivity());
        mParam.nodedataId = mRootView.getActivity().getIntent().getStringExtra(AppConst.ID);
        mRootView.getTvAddress().setText(mRootView.getActivity().getIntent().getStringExtra(AppConst.RECEIVABLEDETAIL_ADDRESS));
        mRootView.getTvCustomerName().setText("产权业主: " + mRootView.getActivity().getIntent().getStringExtra(AppConst.RECEIVABLEDETAIL_NAME_TEL));
        mImm = (InputMethodManager) mRootView.getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        mPhone = mRootView.getActivity().getIntent().getStringExtra(AppConst.RECEIVABLEDETAIL_TEL_PHONE);

        initView();
        initListener();
        queryByNodedataId();
    }

    private void queryByNodedataId() {
        mModel.queryByNodedataId(mParam)
        .subscribeOn(Schedulers.io())
        .retryWhen(new RetryWithDelay(2, 2))//遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
        .doOnSubscribe(disposable -> {

        }).subscribeOn(AndroidSchedulers.mainThread())
        .observeOn(AndroidSchedulers.mainThread())
        .doFinally(() -> {

        })
        .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
        .subscribe(new ErrorHandleSubscriber<BaseResponse<PropertyCharge.NodedataDetail>>(mErrorHandler) {
            @Override
            public void onNext(BaseResponse<PropertyCharge.NodedataDetail> response) {
                if(response.getStatus().equals(BaseAppConst.OUT_TOKEN)){
                    MyApplication.getInstance().gotoLoginActivity();
                }
                if(!response.isSuccess()){
                    ArmsUtils.makeText(mApplication, response.getStatuMsg());
                    mRootView.getEmptyLayout().ERROR_TIP = response.getStatuMsg();
                    mRootView.getEmptyLayout().setEmptyStatus(mRootView.getEmptyLayout().STATUS_ERROR);
                    return;
                }
                mCostItems.addAll(response.getData().bills);
                if(mCostItems.size() > 0){
                    mRootView.getGroupFunction().setVisibility(View.VISIBLE);
                    mRootView.getEmptyLayout().hide();
                }else{
                    mRootView.getGroupFunction().setVisibility(View.GONE);
                    mRootView.getEmptyLayout().setEmptyStatus(mRootView.getEmptyLayout().STATUS_NO_DATA);
                }
                if(null != response.getData().info && response.getData().info.size() > 0){
                    PropertyCharge.NodedataDetail.Info info = response.getData().info.get(0);
                    mRootView.getTvAddress().setText(info.addr);
                    mRootView.getTvCustomerName().setText("产权业主: " + info.custName + "/" + info.custTel);
                    mPhone = info.custTel;
                }
                mAdapter.notifyDataSetChanged();
            }

            @Override
            public void onError(Throwable t) {
                super.onError(t);
                mRootView.getEmptyLayout().setEmptyStatus(mRootView.getEmptyLayout().STATUS_ERROR);
            }
        });
    }

    private void initListener() {
        mRootView.getSwitchChecked().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mShoukuan.size() == mCostItems.size()){
                    isSelectAll = false;
                    mShoukuan.clear();
                }else{
                    isSelectAll = true;
                    mShoukuan.clear();
                    mShoukuan.addAll(mCostItems);
                }
                for (PropertyCharge.NodedataDetail.Bills costItem : mCostItems)
                    costItem.isCheck = isSelectAll;
                mAdapter.notifyDataSetChanged();
                toCalculateTotalPrice();
            }
        });

        mRootView.getTvCommit().setOnClickListener(v -> dialogPayment());
    }

    private void initView() {
        mAdapter = new ReceivableDetailViewAdapter(mCostItems, new ReceivableDetailViewAdapter.OnReceivableDetailListener() {
            @Override
            public void onClick(int position) {
                PropertyCharge.NodedataDetail.Bills costItem = mCostItems.get(position);
                if(costItem.isCheck){
                    mShoukuan.remove(costItem);
                    costItem.isCheck = false;
                }else{
                    mShoukuan.add(costItem);
                    costItem.isCheck = true;
                }
                mAdapter.notifyItemChanged(position);
                toCalculateTotalPrice();
            }
        });
        mRootView.getListview().setAdapter(mAdapter);
    }

    /**
     * 价格计算
     */
    private void toCalculateTotalPrice() {
        totalPrice = 0.00;
        for (PropertyCharge.NodedataDetail.Bills costItem : mShoukuan)
            totalPrice = DoubleUtil.add(totalPrice, costItem.c_uncollected_amount);

        if(mShoukuan.size() == mCostItems.size()){
            mRootView.getSwitchChecked().setImageResource(R.mipmap.propertyfee_ic_select_press);
        }else{
            mRootView.getSwitchChecked().setImageResource(R.mipmap.propertyfee_ic_select_normal);
        }
        mRootView.getTvTotalPrice().setText(totalPrice+"");
//        mRootView.getTvTotalPrice().setText(TextViewUtils.getAmount2(totalPrice));
    }

    PaymentSelectDialog.Builder mPaymentSelectDialog;
    private void dialogPayment(){
        if(mShoukuan.size() == 0){
            ArmsUtils.makeText(mApplication, "请选择费项");
            return;
        }
        if(mPaymentSelectDialog != null){
            mPaymentSelectDialog.show();
        }else{
            mPaymentSelectDialog = new PaymentSelectDialog.Builder(mRootView.getActivity());
            mPaymentSelectDialog.setTitle("请选择支付方式")
            .setProperty(new PaymentSelectDialog.OnPaymentListener() {
                @Override
                public void onClick(String paytype) {
                    ArmsUtils.makeText(mApplication, paytype + "二维码生成");

                    String billIds = "";
                    for (int i = 0; i < mShoukuan.size(); i++) {
                        if(i==0){
                            billIds += "" + mShoukuan.get(i).l_id;
                        }else {
                            billIds += "," + mShoukuan.get(i).l_id;
                        }
                    }
                    ARouter.getInstance().build("/propertyfee/activity/QrCodeCollectionActivity")
                            .withString(AppConst.RECEIVABLE_DETAIL_BILL_IDS, billIds.substring(1, billIds.length()))
                            .withString(AppConst.RECEIVABLE_DETAIL_BILL_TYPE, mShoukuan.size() > 1 ? "2" : "1")
                            .withString(AppConst.RECEIVABLE_DETAIL_BILL_MONEY, totalPrice+"")
                            .withString(AppConst.ID, mParam.nodedataId)
                            .navigation();

                    mPaymentSelectDialog.dismiss();

                }

                //点击现金收款
                @Override
                public void onClick(String paytype, String name) {
                    if("".equals(name)){
                        ArmsUtils.makeText(mApplication, "请选择或输入付款人");
                        return;
                    }
                    payname = name;
                    postCash();
                    mPaymentSelectDialog.dismiss();
                }

                @Override
                public void onHidden(EditText editText) {
                    mImm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
                }
            })
            .create()
            .show();
            mPaymentSelectDialog.updateData();
        }
        mPaymentSelectDialog.updateData(mShoukuan);
    }

    //提交现金收款接口
    private void postCash() {
//        mParamCash.id = mParam.nodedataId;
        String billIds = "";
        for (int i = 0; i < mShoukuan.size(); i++) {
            if(i==0){
                billIds += "" + mShoukuan.get(i).l_id;
            }else {
                billIds += "," + mShoukuan.get(i).l_id;
            }
        }
        mParamCash.ids = billIds;
        mParamCash.userid = BaseAppConst.accountInfo.getUserId()+"";
        mParamCash.userName= BaseAppConst.accountInfo.getUserName();
        mParamCash.paymentName= payname;
//        paymentName//付款人
        mModel.postCash(mParamCash)
                .subscribeOn(Schedulers.io())
                .retryWhen(new RetryWithDelay(2, 2))//遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
                .doOnSubscribe(disposable -> {

                }).subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(() -> {

                })
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .subscribe(new ErrorHandleSubscriber<BaseResponse<String>>(mErrorHandler) {
                    @Override
                    public void onNext(BaseResponse<String> response) {
                        if(response.getStatus().equals(BaseAppConst.OUT_TOKEN)){
                            MyApplication.getInstance().gotoLoginActivity();
                        }
                        if(!response.isSuccess()){
                            ArmsUtils.makeText(mApplication, response.getStatuMsg());
                            return;
                        }
                        if(!response.getData().isEmpty()){
                            ArmsUtils.makeText(mApplication, "成功收款");
                            mRootView.getTvCommit().setClickable(false);
                            getDetail(response.getData());//开获取账单详情
                        }
                    }
                });
    }

    //获取账单详情
    private void getDetail(String id) {//账单id
        mWaitDialog.showWaitingDialog(ArmsUtils.getString(mApplication, R.string.data_load));
        mParamdetail.id= id;
        //假数据
//        mParamCash.id = "177";
        mModel.getDetail(mParamdetail)
                .subscribeOn(Schedulers.io())
                .retryWhen(new RetryWithDelay(2, 2))//遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
                .doOnSubscribe(disposable -> {

                }).subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(() -> {

                })
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .subscribe(new ErrorHandleSubscriber<BaseResponse<List<PropertyCharge.RecordDetail>>>(mErrorHandler) {
                    @Override
                    public void onNext(BaseResponse<List<PropertyCharge.RecordDetail>> response) {
                        if(response.getStatus().equals(BaseAppConst.OUT_TOKEN)){
                            MyApplication.getInstance().gotoLoginActivity();
                        }
                        if(!response.isSuccess()){
                            ArmsUtils.makeText(mApplication, response.getStatuMsg());
                            return;
                        }

                        mRecordDetailList.addAll(response.getData());

                        if (null != mRecordDetailList && mRecordDetailList.size() > 0) {
                            mRecordDetail = mRecordDetailList.get(0);
                            print();//开始打印
                        }
                        mWaitDialog.hideWaitingDialog();
                    }
                });
    }

    public void print() {
        if(Build.MODEL.equals("V1s")){
            AidlUtil.getInstance().initPrinter();
//            AidlUtil.getInstance().connectPrinterService(mRootView.getActivity());
            if(AidlUtil.getInstance().isConnect()){
                setPrintUiV1s();//设置打印数据
                for (int i = 0; i <2 ; i++) {
                    AidlUtil.getInstance().printText("\t\t\t\t\t\t\t\tXXX物业账单信息", 34, true, false);
                    AidlUtil.getInstance().printText(content.toString()+"\n\n\n\n\n", 24, false, false);
                }
                mRootView.getActivity().finish();
                EventBus.getDefault().post(properFeeEvent);
            }else {
                ArmsUtils.snackbarText("打印服务启动失败");
            }
        }else if(Build.MODEL.equals("K-Link V6")){
            ArmsUtils.snackbarText("打印");
        }
    }

    private void setPrintUiV1s(){
        content = new StringBuffer();
        content.append("账单编号: " + mRecordDetail.c_payment_no);
        content.append("\n收款时间: " + mRecordDetail.d_receipt_date);
        content.append("\n住    址: " + mRecordDetail.addr);
        content.append("\n姓    名: " + mRecordDetail.c_payment_name);
        content.append("\n收 款 人: " + mRecordDetail.c_payee_name);
        content.append("\n收款方式: " + mCollectionType[mRecordDetail.c_collection_type]);
        content.append("\n-------------------------------");
        content.append("\n\t\t\t\t名称\t\t\t\t\t\t\t\t用量\t\t\t\t\t\t\t\t单价\t\t\t\t\t\t\t\t小计");
        for (int i = 0; i < mRecordDetailList.size(); i++) {
            content.append("\n\t\t\t\t"+mRecordDetailList.get(i).c_fee_type_name+"\t\t\t\t\t\t\t\t"+mRecordDetailList.get(i).c_quantity+"\t\t\t\t\t\t\t\t"+mRecordDetailList.get(i).c_price+"\t\t\t\t\t\t\t\t"+mRecordDetailList.get(i).countAmount);
        }
        content.append("\n\t\t\t\t"+mRecordDetail.c_fee_type_name+"\t\t\t\t\t\t\t\t"+mRecordDetail.c_quantity+"\t\t\t\t\t\t\t\t"+mRecordDetail.c_price+"\t\t\t\t\t\t\t\t"+mRecordDetail.countAmount);
        content.append("\n-------------------------------");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
        this.mCostItems = null;
        this.mShoukuan = null;
        this.mAdapter = null;
        this.mParam = null;
        this.mPaymentSelectDialog = null;
        this.mImm = null;
    }

    /**
     * 打电话
     */
    public void toPlayPhone() {
        if("".equals(mPhone)){
            ArmsUtils.makeText(mApplication, "当前业主手机号不存在");
            return;
        }
        Intent dialIntent =  new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" +  mPhone));//跳转到拨号界面，同时传递电话号码
        mRootView.getActivity().startActivity(dialIntent);
    }
}
